﻿Imports TBCC.UtilityMobile
Public Class TerminalConnectForm

    Private _pi As ProjectItem
    Private _oldConnectType As Integer
    Private _ConnectType As Integer
    Private _ComNumber As Integer
    Private _Phone As String

    Private Sub ConnectForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        For Each com As String In System.IO.Ports.SerialPort.GetPortNames()
            Me.cboCOM.Items.Add(com)
        Next

        '_pi = MainForm.pi

        LoadData()

    End Sub

    Private Sub LoadData()

        Try


            If KeyValuePairClass.GetValue1("ConnectType") = "" Then
                KeyValuePairClass.SetValue1("ConnectType", "1")
            End If
            If KeyValuePairClass.GetValue1("ComNumber") = "" Then
                KeyValuePairClass.SetValue1("ComNumber", "6")
            End If

            _ConnectType = KeyValuePairClass.GetValue1("ConnectType")
            _ComNumber = KeyValuePairClass.GetValue1("ComNumber")
            _Phone = KeyValuePairClass.GetValue1("Phone")
            _oldConnectType = _ConnectType

            Select Case _ConnectType
                Case 0 '拨号
                    Me.optDial.Checked = True
                    Me.cboCOM.SelectedItem = "COM" & _ComNumber
                    Me.txtPhone.Text = _Phone

                Case 1 '直连
                    Me.optCOM.Checked = True
                    Me.cboCOM.SelectedItem = "COM" & _ComNumber
                    Me.txtIPAddress.Text = _Phone

                Case 2 'TCP
                    Me.optTcp.Checked = True
                    Me.txtIPAddress.Text = _Phone
                    Me.nudIPPort.Value = _ComNumber

            End Select

        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try

        '_oldConnectType = _pi.ConnectType

        'Select Case _pi.ConnectType
        '    Case 0 '拨号
        '        Me.optDial.Checked = True
        '        Me.cboCOM.SelectedItem = "COM" & _pi.ComNumber
        '        Me.txtPhone.Text = _pi.Phone

        '    Case 1 '直连
        '        Me.optCOM.Checked = True
        '        Me.cboCOM.SelectedItem = "COM" & _pi.ComNumber

        '    Case 2 'TCP
        '        Me.optTcp.Checked = True
        '        Me.txtIPAddress.Text = _pi.Phone
        '        Me.nudIPPort.Value = _pi.ComNumber

        'End Select
    End Sub

    Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click
        Me.btnOk.Enabled = False

        If CheckValid() = True Then
            If Save() = True Then
                Connect()
                'If Connect() = True Then
                '    Me.DialogResult = Windows.Forms.DialogResult.OK
                '    Me.Close()
                'End If
            End If
        End If

        Me.btnOk.Enabled = True
    End Sub

    Private Function Save() As Boolean
        Try
            If Me.optCOM.Checked = True Then
                _ConnectType = 1
                _ComNumber = Me.cboCOM.SelectedItem.Substring(3)
                _Phone = Me.txtPhone.Text
                '_pi.ConnectType = 1
                '_pi.ComNumber = CInt(Me.cboCOM.SelectedItem.Substring(3))
                g_BackgroundUploadHistoryData = True
                g_BackgroundUploadAlarm = True

            ElseIf Me.optDial.Checked = True Then
                _ConnectType = 0
                _ComNumber = Me.cboCOM.SelectedItem.Substring(3)
                _Phone = Me.txtPhone.Text
                '_pi.ConnectType = 0
                '_pi.ComNumber = CInt(Me.cboCOM.SelectedItem.Substring(3))
                '_pi.Phone = Me.txtPhone.Text
                g_BackgroundUploadHistoryData = False
                g_BackgroundUploadAlarm = False

            ElseIf Me.optTcp.Checked = True Then
                _ConnectType = 2
                _ComNumber = CInt(Me.nudIPPort.Value)
                _Phone = Me.txtIPAddress.Text
                '_pi.ConnectType = 2
                '_pi.Phone = Me.txtIPAddress.Text
                '_pi.ComNumber = Me.nudIPPort.Value
                g_BackgroundUploadHistoryData = False
                g_BackgroundUploadAlarm = False

            End If

            KeyValuePairClass.SetValue("0", "ConnectType", _ConnectType)
            KeyValuePairClass.SetValue("0", "ComNumber", _ComNumber)
            KeyValuePairClass.SetValue("0", "Phone", _Phone)

        Catch ex As Exception
            'msg.ShowError("")
            Return False
        End Try

        Return True


        'Dim strSql As String

        'strSql = "UPDATE tbccProject SET " & _
        '        "ConnectType=?,ComNumber=?,phoneNumber=? " & _
        '        "WHERE projectID=?"

        'Dim p(3) As MySql.Data.MySqlClient.MySqlParameter
        'For i As Integer = 0 To p.Length - 1
        '    p(i) = New MySql.Data.MySqlClient.MySqlParameter()
        'Next

        'p(0).Value = _pi.ConnectType
        'p(1).Value = _pi.ComNumber
        'p(2).Value = _pi.Phone
        'p(3).Value = _pi.ProjectID

        'If SqlHelper.ExecuteNonQuery(strSql, p) > 0 Then
        '    If _pi.ConnectType <> _oldConnectType Then
        '        KeyValuePairClass.SetValue(_pi.ProjectID, "BackgroundUploadHistoryData", IIf(g_BackgroundUploadHistoryData, 1, 0))
        '        KeyValuePairClass.SetValue(_pi.ProjectID, "BackgroundUploadAlarm", IIf(g_BackgroundUploadAlarm, 1, 0))
        '    End If

        '    Return True
        'Else
        '    Return False
        'End If

    End Function

    Private Function CheckValid() As Boolean
        '检查连接方式
        If Me.optCOM.Checked = False AndAlso Me.optDial.Checked = False AndAlso Me.optTcp.Checked = False Then
            msg.Show("请选择连接方式。")
            Me.optCOM.Focus()
            Return False
        End If

        '检查串口号
        If Me.optCOM.Checked = True OrElse Me.optDial.Checked = True Then
            If Me.cboCOM.SelectedIndex < 0 Then
                msg.Show("请选择串口号。")
                Me.cboCOM.Focus()
                Return False
            End If
        End If

        '检查电话号码
        If Me.optDial.Checked = True Then
            If Me.txtPhone.Text.Trim.Length <= 0 Then
                msg.Show("请输入电话号码。")
                Me.txtPhone.Focus()
                Return False
            End If
        End If

        '检查TCP参数
        If Me.optTcp.Checked = True Then
            '检查IP地址
            If Me.txtIPAddress.Text.Trim.Length <= 0 Then
                msg.Show("请输入IP地址。")
                Me.txtIPAddress.Focus()
                Return False
            End If
            '检查IP端口
            If Me.nudIPPort.Value <= 0 Then
                msg.Show("IP端口不能为零。")
                Me.nudIPPort.Focus()
                Return False
            End If
        End If

        Return True
    End Function

    Private Sub SwitchPanel(ByVal isShowMain As Boolean)
        If Me.InvokeRequired Then
            Me.Invoke(New Action(Of Boolean)(AddressOf _SwitchPanel), isShowMain)
        Else
            _SwitchPanel(isShowMain)
        End If
    End Sub
    Private Sub _SwitchPanel(ByVal flag As Boolean)
        Me.pnlMain.Visible = flag
        Me.pnlWaiting.Visible = Not flag
    End Sub

    Private Sub ConnectSucceed(ByVal result As Boolean)
        If Me.InvokeRequired Then
            Me.Invoke(New Action(Of Boolean)(AddressOf _ConnectSucceed), result)
        Else
            _ConnectSucceed(result)
        End If
    End Sub
    Private Sub _ConnectSucceed(ByVal result As Boolean)
        If result = True Then
            'Dim mainForm As TerminalForm = Nothing
            'If TypeOf Me.MyParentForm Is TerminalForm Then
            '    mainForm = Me.MyParentForm
            'End If

            'If mainForm IsNot Nothing Then
            '    TerminalForm.IsConnected = True
            '    mainForm.SetControlEnabled(True)
            '    mainForm.SetToolsBarPrjActive(Not (_pi.LocalRunStatus = LocalRunStatus.Start))
            '    mainForm.SetText(String.Format("终端管理器 [终端:{0}]", _pi.ProjectName), False)
            'End If

            Me.DialogResult = Windows.Forms.DialogResult.OK
            Me.Close()
        Else
            SwitchPanel(True)
        End If
        Me.Cursor = Cursors.Default
    End Sub

#Region " 连接函数 "

    Private Delegate Function BoolMethodHandler() As Boolean
    Private Sub Connect()
        Me.Cursor = Cursors.WaitCursor
        Dim handler As New BoolMethodHandler(AddressOf _Connect)
        Dim asynCallback As New AsyncCallback(AddressOf ConnectCompleted)
        handler.BeginInvoke(asynCallback, handler)
        SwitchPanel(False)
    End Sub
    Private Sub ConnectCompleted(ByVal ar As System.IAsyncResult)
        Dim handler As BoolMethodHandler
        handler = ar.AsyncState

        Dim result As Boolean = False
        If handler IsNot Nothing Then
            result = handler.EndInvoke(ar)
        End If

        ConnectSucceed(result)
    End Sub

    Private Function _Connect() As Boolean
        Return Connect(False)
    End Function
    Private Function Connect(ByVal isRetry As Boolean) As Boolean

        COMHelper.ConnectType = _ConnectType

        If _ConnectType = 1 Then
            '直连 
            'Me.Cursor = Cursors.WaitCursor
            If InitCOM() = False Then
                Return False
            End If
            'Me.Cursor = Cursors.Default
        ElseIf _ConnectType = 0 Then
            '拨号
            Dim frm As New DialForm("COM" & _ComNumber, _Phone)
            If frm.ShowDialog <> Windows.Forms.DialogResult.OK Then
                Return False
            End If
        Else
            'TCP/IP
            Dim frm As New TcpConnectForm(isRetry, _Phone, _ComNumber)
            If frm.ShowDialog() <> Windows.Forms.DialogResult.OK Then
                Return False
            End If
        End If

        Return True
    End Function

#Region " 直连方式 "

    Private Function InitCOM() As Boolean
        Dim com As String

        ' Dim cmd As String

        'cmd = String.Format("AT^STANDARDCLOCK+=SW\r\n")

        com = _ComNumber.ToString()

        If com = String.Empty Then
            msg.Show("请先配置串口。")
            Return False
        End If


        If COMHelper.Instance.InitSerialPort(com.Replace("COM", ""), IO.Ports.Parity.Even) Then


            'COMHelper.Instance.WriteCommand(cmd)

            'System.Threading.Thread.Sleep(5000)


            Return DirectConnect()
        Else
            msg.ShowError("初始化串口失败,请检查串口配置。")
            Return False
        End If
    End Function

    Private Function DirectConnect() As Boolean
        Dim buf As Short() = Nothing
        Dim pacID As String = Nothing
        Dim devType As Integer = Nothing
        Dim writeState As Integer = Nothing

        Return True


FailedHandler:
        msg.ShowError("未检测到终端连接。")
        Return False

    End Function

#End Region

    Private Sub ShowAddNewForm(ByVal pi As ProjectItem)
        Me.Invoke(New Action(Of ProjectItem)(AddressOf _ShowAddNewForm), pi)
    End Sub
    Private Sub _ShowAddNewForm(ByVal pi As ProjectItem)
        'Dim frm As New TerminalAddNewForm(pi)
        'If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
        '    Me.MyParentForm.HasNewPrj = True
        'Else
        '    Me.MyParentForm.HasNewPrj = False
        '    Me.MyParentForm.mnuHisDataUpload.Enabled = False
        '    Me.MyParentForm.tsbHisDataUpload.Enabled = False
        'End If
    End Sub

#End Region

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Close()
    End Sub

    Private Sub optDial_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optDial.CheckedChanged
        Me.pnlTCP.Enabled = False
        Me.pnlTCP.Visible = False
        Me.pnlCom.Enabled = True
        Me.pnlCom.Visible = True
        Me.pnlPhone.Enabled = True
        Me.pnlPhone.Visible = True
    End Sub

    Private Sub optCOM_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optCOM.CheckedChanged
        Me.pnlTCP.Enabled = False
        Me.pnlTCP.Visible = False
        Me.pnlPhone.Enabled = False
        Me.pnlPhone.Visible = False
        Me.pnlCom.Enabled = True
        Me.pnlCom.Visible = True
    End Sub

    Private Sub optTcp_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optTcp.CheckedChanged
        Me.pnlCom.Enabled = False
        Me.pnlCom.Visible = False
        Me.pnlPhone.Enabled = False
        Me.pnlPhone.Visible = False
        Me.pnlTCP.Enabled = True
        Me.pnlTCP.Visible = True
    End Sub

    Private Sub btnConnectConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnectConfig.Click
        'Dim parameters(2) As String

        'parameters(0) = KeyValuePairClass.GetValue(_pi.ProjectID, "ClientSocket_Heartbeat_IdleTime")
        'parameters(1) = KeyValuePairClass.GetValue(_pi.ProjectID, "ClientSocket_Heartbeat_WaitTime")
        'parameters(2) = KeyValuePairClass.GetValue(_pi.ProjectID, "ClientSocket_Heartbeat_Rep")

        'Dim frm As New ConnectConfigForm(parameters)
        'If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
        '    KeyValuePairClass.SetValue(_pi.ProjectID, "ClientSocket_Heartbeat_IdleTime", parameters(0))
        '    KeyValuePairClass.SetValue(_pi.ProjectID, "ClientSocket_Heartbeat_WaitTime", parameters(1))
        '    KeyValuePairClass.SetValue(_pi.ProjectID, "ClientSocket_Heartbeat_Rep", parameters(2))
        'End If
    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    End Sub

    Public Sub New()

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub
End Class